<?php

class DomainLookup {
	
	// Kicks off a process to lookup domain to determine if it runs Google Apps
	public static function GoogleAppsLookup($email) {
		$dir = dirname(__FILE__);
		$user_id = $_SESSION["user_id"];
		if (Util::isNullOrEmpty($user_id)) return;
		
		Util::debug("GoogleAppsLookup for {$email}");
		
		$user = new InsightUser($user_id);
		// if they've permanently dismissed the invites, don't show them.
		if ($user->dismiss_google_domain_lookups) return false;
		
		// only display if they've been using Cirrus Insight for at least 2 weeks
		$two_weeks = 1209600;
		$now = time();
		$signup_date = strtotime($user->signup_date);
		if ($now - $signup_date < $two_weeks) return false;

		$domain = substr($email, stripos($email, '@')+1);
		// don't display if it's the contact record for someone from their domain/organization
		if (stripos($user->email, "@{$domain}") !== FALSE) {
			return false;
		}
		
		// TODO: Remove
		return false;
		
		// sub-population definition for A/B testing
		// Only include people with the following user ID prefix: 005A, 0059
		// also include me
		$subpop = array('005A', '0059');
		if (in_array(substr($user_id, 0, 4), $subpop) === FALSE && $user_id != '00530000004CrKaAAK') {
			Util::debug("bailing...");
			return false;
		}
		
		$redis = Database::connect();

		$lookup = $redis->get("galookup:{$domain}");
		Util::debug("GoogleAppsLookup: galookup:{$domain}", $lookup);
		if ($lookup == "yes") {
			// Domain has Google Apps
			// Check invitation status
			
			$invite = $redis->get("invite:{$user_id}:{$email}");
			if ($invite === FALSE) {
				// email hasn't been added, but the domain is known
				$redis->set("invite:{$user_id}:{$email}", "invite");
				return true;
			} else {
				// key is present
				// if they've already sent the invite, or dismissed the invite, return false
				if ($invite == "invite") {
					return true;
				}
				return false;
			}
		} else if ($lookup == "no") {
			// domain does not use google apps
			return false;
		} else {
			// haven't done a lookup yet
			$command = "php {$dir}/../async/galookup.php {$user_id} {$email}";
			Util::debug("Domain Lookup", $command);
			exec($command . " > /dev/null 2>&1 &");
			
			// return false for now
			return false;
		}
	}
	
}

?>